Our logo showing our story of the brand without any words.
Introduction to Microsoft Excel VBA
VBA is the acronym for Visual Basic for Applications. It is an integration of the Microsoft’s event-driven programming language Visual Basic with Microsoft Office applications such as Microsoft Excel. Excel VBA means Excel Visual Basic for Applications which can be created using the built-in Visual Basic Editor in Microsoft Excel, and you can use it to customize and extend the capabilities of MS Excel. An application created by Excel VBA is also known as macro. Our tutorial is based on MS Excel 2003. We shall show you how to create Excel VBA in easy steps.
There are two methods which you can create an Excel VBA. The first is to place a command button on the MS Excel spreadsheet and click on the button to enter the Visual Basic Editor. The second is to launch the Visual Basic Editor from the menu. To launch the VBE, click on tools on the menu bar and select macro and then click on Visual Basic Editor.
To create an Excel VBA using the command button, you need to place it on the spreadsheet. In order to access the command button, you need to click View on the MS Excel menu bar and then click on the toolbar and select the Control Toolbox to launch the control toolbox, as shown in Figure 1.1 .The control toolbox comprises various controls, as shown in Figure 1.2. Select the command button and place it on the spreadsheet.
>
Next, you click on the command button and the Visual Basic Editor will appear. Enter the statement as shown in the figure. The first statement will fill up cell A1 to cell A10 with the phrase "Visual Basic" while the second statement add the value in cell A11 and cell B11 and then show the sum in cell C11. It is that simple.
To launch the VBE, click on tools on the menu bar and select macro and then click on Visual Basic Editor,as shown in Figure 1.3. The Visual Basic Editor code window is shown in Figure 1.4. You can create a VBA function in the VBE. We will learn about function in later lesson.
Variables are like mail boxes in the post office. The content of the variables changes every now and then, just like the mail boxes. In Excel VBA, variables are areas allocated by the computer memory to store data. Like the mail boxes, each variable must be given a name.
The following are the rules when naming the variables in Excel VBA
They must not exceed 40 characters
They must contain only letters, numbers and underscore chacaters
No spacing is allowed
It must not begin with a number
Period is not permitted
Examples of valid and invalid variable names are displayed in Table 2.1
Valid Name | Invalid Name | |
My_Car | My.Car | |
ThisYear | 1NewBoy | |
Long_Name_Can_beUSE | He&HisFather | *& is not acceptable |
Group88 | Student ID | * Spacing not allowed |
Excel VBA data types can be grossly divided into two types, the numeric data types and non-numeric data types. They are classified below:
Numeric data types are types of data that consist of numbers, which can be computed mathematically with various standard aritmetic operators such as add, minus, multiply, divide and so on. In Excel VBA, the numeric data are divided into 7 types, which are summarized in Table 2.2
The nonnumeric data types are summarized in Table 2.3
Data Type | Storage | Range |
String(fixed length) | Length of string | 1 to 65,400 characters |
String(variable length) | Length + 10 bytes | 0 to 2 billion characters |
Date | 8 bytes | January 1, 100 to December 31, 9999 |
Boolean | 2 bytes | True or False |
Object | 4 bytes | Any embedded object |
Variant(numeric) | 16 bytes | Any value as large as Double |
Variant(text) | Length+22 bytes | Same as variable-length string |
Table 2.3: Nonnumeric Data Types
In Excel VBA, we needs to declare the variables before using them by assigning names and data types. You can declare the variables implicitly or explicitly.
We can use a variable without openly(explicitly) declare it if we assign an initial value to it. For example,
MyFirstName="John" MyAge=32
Excel VBA automatically create two varaibles MyFirstName and MyAge as variants, and they are assigned data as John and 32 respectively. This type of declaration is called implicit declaration.
Implicit declaration of variable often lead to errors in writing code therefore it is better to declare a variable explicitly. Variables are normally declared in the general section of the codes' window using the Dim statement.
The syntax is as follows:
Dim | password | As | String |
Dim | yourName | As | String |
Dim | firstnum | As | Integer |
Dim | secondnum | As | Integer |
Dim | total | As | Integer |
Dim BirthDay As Date |
You may also combine them in one line, separating each variable with a comma, as follows:
Dim password As String, yourName As String, firstnum As Integer.
If the data type is not specified, Excel VBA will automatically declare the variable as a Variant. For string declaration, there are two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length string, just use the same format as Example 2.1 above. However, for the fixed- length string, you have to use the format as shown below:
Dim VariableName as String * n
where n defines the number of characters the string can hold. For example, Dim yourName as String * 10 mean yourName can hold no more than 10 Characters.
In this example, we declared three types of variables, namely the string, date and currency.
Private Sub CommandButton1_Click() Dim YourName As String
Dim BirthDay As Date Dim Income As Currency
YourName = "Alex" BirthDay = "1 April 1980"
Income = 1000 Range("A1") = YourName Range("A2") = BirthDay Range("A3") = Income End Sub
When we work with a single item, we only need to use one variable. However, if we have a list of items which are of similar type to deal with, we need to declare an array of variables instead of using a variable for each item. For example, if we need to enter one hundred names, instead of declaring one hundred different variables, we need to declare only one array. By definition, an array is a group of variables with the same data type and name. We differentiate each item in the array by using subscript, the index value of each item, for example name (1), name (2), name (3) .......etc.
We use the Dim statement to declare an array just as the way we declare a single variable.In Excel VBA, we can have a one dimensional array, two dimensional array or even a multidimensional array (up to 60)
The general statements to declare a one dimensional array in Excel VBA is as follows: Dim arrayName(index) as dataType or
Dim arrayName(first index to last index) as dataType For example,
Dim StudentName(10) as String Dim StudentName(1 to 10) as String
Dim StudentMark(10) as Single
Dim StudentMark( 1 to 10) as Single Example 3.1
In this example, we define an array StudentName of five strings using the Dim keyword. We include an InputBox to accept input from the user. We also use the For ...Next loop to accept the input five times and display the five names from cell A1 to cell E1. The code is as follows:
Private Sub CommandButton1_Click( )
Dim | StudentName(1 | to | 5) | As | String | ||
For | i | = | 1 | To | 5 |
StudentName(i) = InputBox("Enter student Name")
Cells(i, 1) = StudentName(i) Next
End Sub
** You can also declare the array using Dim StudentName(5) As String
When we run the program, an input box will appear, as shown below. This input box will repeat five times and let the user enter five names.
The five names will be displayed in the spreadsheet as shown below:
You can also declare more than one array in a single line. In this example, we declare three arrays in a single line, separated by commas.
Private Sub CommandButton1_Click( )
Dim StudentName(3) As String, StudentID(3) As String, StudentMark(3) As Single For i = 1 To 3
StudentName(i) = InputBox("Enter student Name") StudentID(i) = InputBox("Enter student ID") StudentMark(i) = InputBox("Enter student Mark") Cells(i, 1) = StudentName(i)
Cells(i, 2) = StudentID(i) Cells(i, 3) = StudentMark(i) Next
End Sub
When we run the program, three input boxes will appear consecutively to let the user enter the student name, the student ID and then the student mark. The process will repeat three times until the particulars of all three students have been entered. The three input boxes and the output are shown below:
Multidimensional arrays are often needed when we are dealing with more complex database, especially those that handle large amount of data. Data are usually organized and arranged in table form, this is where the multidimensional arrays come into play. However, in this tutorial, we are dealing only with the two dimensional array. Two dimensional array can be represented by a table that contains rows and columns, where one index represents the rows and the other index represent the columns.
The format to declare a two dimensional array is
Where num1 is the suffix of the first dimension of the last element and num2 is the suffix of the second dimension of the last element in the array. The suffixes of the element in the array will start with (0, 0) unless you set the Option Base to 1. In the case when the Option Base is set to 1, then the suffixes of the element in the array will start with (1, 1). For example,
Dim Score (3, 3) as Integer
will create a two dimension array consists of 16 elements. These elements can be organized in a table form as shown in the table below:
Score(0,0) | Score(0,1) | Score(0,2) | Score(0,3) |
Score(1,0) | Score(1,1) | Score(1,2) | Score(1,3) |
Score(2,0) | Score(2,1) | Score(2,2) | Score(2,3) |
Score(3,0) | Score(3,1) | Score(3,2) | Score(3,3) |
If you set the option base to 1, then there will be only 9 elements, i.e from Score(1,1) to Score(3,3). However, if you want the first element to start with suffixes (1,1) you can also use the following format of declaration:
Dim Score(1 to 3, 1 to 3) as Integer
If a company wants to track the performance of 5 salespersons over a period of 2 days, you can create a 5x2 array in Excel VBA, denoted by a 5X 2 table in a spreadsheet.
You can write the following VBA code: Private Sub CommandButton1_Click() Dim SalesVolume(2to 6, 2 to 3) as Single
Dim SalesPerson as Integer, Day as Integer For SalesPerson=2 to 6
For Day=2 to3
SalesVolume(SalesPerson, Day)=inputbox("Enter Sales Volume") Cells(SalesPerson, Day)=SalesVolume(SalesPerson,Day)
Next Day
Next SalesPerson End Sub
When the program is run, the inputbox that will prompt the user to enter sales volume will appear 10 times, as shown below:
After all the sales Volumes are entered, the values in the spreadsheet are shown below:
If you need to make sure the user enters the correct sales volume, you can change line 5 statement to SalesVolume(SalesPerson, Day) = InputBox("Enter Sales Volume of " & " SalesPerson " & (SalesPerson - 1) &
Day " & (Day - 1))
A clearer instruction will be shown as follows:
Operators are important in writing Excel VBA program code. They are used to calculate values, perform certain operations, make comparisons and more. The operators can be divided into three main categories:
Arithmetic
Comparison
Logical
Arithmetic operators are used to perform mathematical operations in Excel VBA.
Operator | Mathematical function | Example | |
^ | Exponential | MsgBox 2^4 gives a value of 16 | |
* | Multiplication | MsgBox 4*3 gives a value of 12, | |
/ | Division | MsgBox 12/4 gives a value of 3 | |
Mod | Modulus (returns the remainder from an integer division) | MsgBox 15 Mod 4 gives value of 3 | |
\ | Integer Division(discards the decimal places) | MsgBox 19\4 gives a value of 4 | |
+ or & | String concatenation | MsgBox "Excel"&"VBA 2010" or "Excel"+"VBA 2010" produces a new string "Excel VBA 2010" |
MsgBox is a built-in function of excel VBA that displays a message. We shall learn more about functions in next lesson. Note that MsgBox 1+"VBA" will produce a type mismatch error whereas MsgBox 1&"VBA" will not result in an error, it gives a concatenated string 1VBA. We shall engage the usage of arithmetic operators in Excel VBA code writing in future lessons.
Comparison If | operators | are | often | used | in | writing code mark>50 | that | require | decisions | making. | For | example, then |
MsgBox | "Pass" | |||||||||||
Else | ||||||||||||
MsgBox | "Fail" | |||||||||||
Endif |
Operator | Meaning | Example |
< | Less than | MsgBox 2<3 returns true while MsgBox 4>5 returns false |
<= | Less than or equal to | MsgBox 3<=4 returns true |
We shall learn more about writing decision making code in future lessons. Here are a list of comparison operators:
> | Greater than | MsgBox 5>4 returns true |
>= | Greater than or equal to | MsgBox 10>=9 returns true |
= | Equal to | MsgBox 10=10 returns true |
<> | Not Equal to | MsgBox 9<>10 returns true |
* For letters, the hierarchy is A>B>C>..........>Z Therefore MsgBox A>B returns true
Logical operators are also used in writing decision making codes by comparing values or expressions.
Operator | Meaning | Example | |
And | Logical Conjunction | If A>=80 And B<101 thenGrade="A" | |
Or | Logical Disjunction | If income>5000 or car>2 thenStatus="Rich" | |
Not | Logical negation | MsgBox Not (3 > 4)returns true | |
Xor | Similar to Or, except that it returns False if both camparison values are true | MsgBox 4 > 3 Xor 5 >2 returns false |
A Subroutine in Excel VBA is a procedure that performs a specific task and to return values, but it does not return a value associated with its name. However, it can return a value through a variable name. Subroutines are usually used to accept input from the user, display information, print information, manipulate properties or perform some other tasks. It is a program code by itself and it is not an event procedure because it is not associated with a runtime procedure or an Excel VBA control such as a command button. It is called by the main program whenever it is required to perform a certain task. Sub procedures help to make programs smaller and easier to manage. A Subroutine begins with a Sub statement and ends with an End Sub statement.
The program structure of a sub procedure is as follows:
Sub subProg(arguments)
Statements End Sub
Subroutines are called by the main program using the Call keyword.
Sub MainProg( )
Call SubProg()
End Sub
A subroutine is different from a function that it does not return a value directly. You can include parameters in a subroutine.
In this example, the main program calls the subroutine findHidden and execute it. The end result is a message box that display the hidden text.
Private Call End Sub hidden_txt MsgBox End Sub | Sub | = | CommandButton1_Click() findHidden Sub findHidden() "@#%43&*" hidden_txt |
Private Sub CommandButton1_Click() Call salary(10, 300) End Sub Sub salary(wage As Single, hours As Single) MsgBox wage * hours End Sub |
In this example, the Call command calls the subroutine salary and passes the parameters 10 and 300 to it. It will calculate the salary based on wage per hour and number of hours and display on the message box.
In Excel VBA, a function is similar to a subroutine but the main purpose of the function is to accept a certain input from the user and return a value which is passed on to the main program to finish the execution. There are two types of functions, the built-in functions (or internal functions) and the functions created by the programmers, or simply called user-defined functions. The first built-in function that we have already learned and familiar with its usage is the Message Box. We are not going to repeat here but we shall take a look at its syntax once more, i.e.
Now we shall examine the next commonly used function in Excel VBA, the InputBox function.
An InputBox( ) function displays a message box where the user can enter a value or a message in the form of text. The syntax is
myMessage is a variant data type but typically it is declared as string, which accept the message input by the users. The arguments are explained as follows:
Prompt represents he message displayed normally as a question asked.
Title represents the title of the Input Box.
default-text represents the default text that appears in the input field where users can use it as his intended input or he may change to the message he wish to key in.
x-position and y-position represents the position or the coordinate of the input box.
Example 5.1
In this example, we insert a label and a command button into the MS Excel spreadsheet. Double click on the command button and enter the Excel VBA code as follows:
Private Sub CommandButton1_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your messge here", 500, 700) If userMsg <> "" Then
MsgBox( userMsg) Else
MsgBox("No Message") End If
End Sub
The InputBox is shown in Figure 5.1
5.2.1 Creating User-Defined Functions
The syntax to create a User-Defined function is as follows: Public Function functionName (Arg As dataType,...) As dataType or
Private Function functionName (Arg As dataType,...) As dataType
Public indicates that the function is applicable to the whole project while Private indicates that the function is only applicable to a certain module or procedure.
In order to create a user-defined function in Excel VBA, you need to go into the Visual Basic Editor in MS Excel Spreadsheet.營n the Visual Basic Editor, click on Insert on the menu bar to insert a module into the project. Enter the following code 燼s shown in Figure 5.2. This function is to calculate the cube root of a number.
Now enter the function CubeRoot just like you enter the formula of MS Excel, as shown in Figure 5.3. The value of cube root for the number in cell C4 will appear in cell D4.
We will deal with more user-defined functions in future lessons
In Excel VBA , we can write codes that can perform arithmetic operations using standard arithmetic operators. However, for more complex mathematical calculations, we need to use the built-in mathematical functions in Excel VBA. There are numerous built-in mathematical functions in Excel VBA. Among them are Abs, Exp, Int, Fix, Rnd, Round, sqr and more. We shall deal with trigonometric functions and Financial Functions in coming lessons.
In Excel VBA, the Abs function returns the absolute value(positive value) of a given number. The syntax is Abs(Number)
Private Sub CommandButton1_Click()
Cells(1,1)=Abs(-100) End Sub
Running the program will displays 100 in cell A1
The Exp of a number x is the value of ex.The syntax is: Exp(Number)
Private Sub CommandButton1_Click() Cells(1,1)=Exp(1)
End Sub
Running the program will displays 2.718282 in cell A1
Int is the function that converts a number into an integer by truncating its decimal part and the resulting integer is the largest integer that is smaller than the number.
The syntax is Int(Number) Example 6.3
Private Sub CommandButton1_Click() Cells(1,1)=Int(2.4)
Cells(2,1)=Int(4.8)
Cells(3,1)=Int(-4.6) Cells(4,1)=Int(0.32) End Sub
Running the program will displays the results as 2 in cell A1,4 in cell A2,-5 in cell A3 and 0 in cell A4.
Fix and Int are the same if the number is a positive number as both truncate the decimal part of the number and return an integer. However, when the number is negative, it will return the smallest integer that is larger than the number. The syntx is:
Private Sub CommandButton1_Click() Cells(1,1)=Fix(2.4)
Cells(2,1)=Fix(4.8)
Cells(3,1)=Fix(-4.6)
Cells(4,1)=Fix(-6.32)
End Sub
Running the program will displays the results as 2 in cell A1,4 in cell A2,-4 in cell A3 and -6 in cell A4.
The Rnd function returns a random value between 0 and 1.Rnd is very useful when we deal with the concept of chance and probability. The syntax is:
Private Sub CommandButton1_Click() Dim x As Integer
For x = 1 To 10 nbsp;Cells(x, 1) = Rnd() Next x
End Sub
Running the program will displays ten random numbers between 0 and 1 from cell A1 to cell A10, as shown in Figure 6.1
Round is the function that rounds up a number to a certain number of decimal places. The Format is Round (n,
m) which means to round a number n to m decimal places. For example, Round (7.2567, 2) =7.26
Sqr is the function that computes the square root of a number. For example, Sqr(4)=2, Sqr(9)=2 and etc.
In previous lesson, we have learned how to write code using various mathematical functions in Excel VBA. In this lesson, we shall proceed to learn how to work with trigonometric functions. The three basic trigonometric functions are Sin, Cos and Tan which stand for sine, cosine and tangent. We also deal with the inverse of tangent, Atn.
The Sin function returns the sine value of an angle. We need to convert the angle to radian as Excel VBA cannot deal with angle in degree. The conversion is based on the following equation:
π radian= 180o so 1o=π/180 radian
The issue is how to get the exact value of p? We can use p=3.14159 but it will not be accurate. To get exact value of π, we use the arc tangent function, i.e. is Atn. Using the equation tan(π/4)=1, so Atn(1)=π/4, therefore, π=4Atn(1)
The syntax of the Sin function in Excel VBA is Sin(Angle in radian)
In this example, we use pi to represent π and assign the value of π using the formula pi = 4*.Atn(1). We use the function Round the value of sine to four decimal places.
Private Sub CommandButton1_Click()
Dim | pi | As | Single | |||||
pi | = | 4*.Atn(1) | ||||||
MsgBox("Sin | 90 | is" | & | Round(Sin(pi/2), | 4)) | |||
End Sub |
Running the program produces the message as shown in Figure 7.1
The Cos function returns the cosine value of an angle The syntax of the Cos function in Excel VBA is Cos(Angle in radian)
p>Private Sub CommandButton1_Click()
Dim pi As Single pi = 4*.Atn(1)
MsgBox("Cos 60 is" & Round(Cos(pi/3), 4)) End Sub
Running the program produces the message as shown in Figure 7.2
Excel VBA uses various built-in functions to handle strings. These string handling functions are Left, Right, Instr, Mid and Len . The following example illustrates the usage of all these functions.
InStr is a function that looks for and returns the position of a substring in a phrase Example 8.1
Private Sub cmdInstr_Click() Dim phrase As String phrase = Cells(1, 1).Value
Cells(4, 1) = InStr(phrase, "ual") End Sub
The function InStr(phrase,"ual") will find the substring "ual" from the phrase "Visual Basic" entered in cells(1,1) and then return its position, in this case, it is 4 from the left.
Left is a function that extracts the characters from a phrase, starting from the left.
Left(phrase,4) means 4 characters are extracted from the phrase, starting from the leftmost position.
Private | Sub | cmdLeft_Click() | ||||
Dim | phrase | As | String | |||
phrase | = | Cells(1, | 1).Value | |||
Cells(2, | 1) | = | Left(phrase, | 4) | ||
End Sub |
This code returns the substring "Visu" from the phrase "Visual Basic" entered in cells(1,1)
Right is a function that extracts characters from a phrase, starting from the Right.
Private Sub cmdRight_Click() Dim phrase As String
phrase = Cells(1, 1).Value Cells(3, 1) = Right(phrase, 5)
This code returns the substring "Basic" from the phrase "Visual Basic" entered in cells(1,1)
Mid is a function that extracts a substring from a phrase, starting from the position specified by the second parameter in the bracket.
Mid(phrase,8,3) means a substring of three characters are extracted from the phrase, starting from the 8th position from the left, including empty space.
Private Sub cmdMid_Click() Dim phrase As String phrase = Cells(1, 1).Value
Cells(5, 1) = Mid(phrase, 8, 3) End Sub
This code returns the substring "Bas" from the phrase "Visual Basic" entered in cells(1,1)
Len is a function that returns the length of a phrase(including empty space in between)
Private | Sub | cmdLen_Click() | ||
Dim | phrase | As | String | |
phrase | = | Cells(1, | 1).Value | |
Cells(6, | 1) | = | Len(phrase) | |
End Sub |
The code returns 12 for the phrase "Visual Basic" entered in cells(1,1)
The output of all the examples are shown in Figure 8.1 below:
The Format function is in Excel VBA can dispaly the numeric values in various formats. There are two types of Format functions, one of them is the built-in Format function while another is the user-defined Format function.
The syntax of the built-in Format function is
General Number | To display the number without having separators between thousands. | Format(8972.234, “General Number”)=8972.234 |
Fixed | To display the number without having separators between thousands and | Format(8972.234, “Fixed”)=8972.23 |
where n is a number and the list of style arguments are listed in Table 9.1 The output is shown in Figure 9.1
rounds it up to two decimal places. | ||
Standard | To display the number with separators or separators between thousands and rounds it up to two decimal places. | Format(6648972.265, “Standard”)= 6,648,972.27 |
Currency | To display the number with the dollar sign in front, has separators between thousands as well as rounding it up to two decimal places. | Format(6648972.265, “Currency”)= $6,648,972.27 |
Percent | Converts the number to the percentage form and displays a % sign and rounds it up to two decimal places. | Format(0.56324, “Percent”)=56.32 % |
Private Sub CommandButton1_Click()
Cells(1, 1) = Format(8972.234, "General Number")
Cells(2, | 1) | = | Format(8972.234, | "Fixed") | |
Cells(3, | 1) | = | Format(6648972.265, | "Standard") | |
Cells(4, | 1) | = | Format(6648972.265, | "Currency") | |
Cells(5, | 1) | = | Format(0.56324, | "Percent") | |
End Sub |
9.2 The User-Defined Format function
The syntax of the user-defined Format function is
Although it is known as user-defined format, we still need to follows certain formatting styles. Examples of user- defined formatting style are listed in Table 9.2
Private Sub CommandButton1_Click()
Cells(1, 1) = Format(781234.57, "0")
Cells(2, 1) = Format(781234.57, "0.0")
Cells(3, 1) = Format(781234.576, "0.00")
Cells(4, 1) = Format(781234.576, "#,##0.00") Cells(5, 1) = Format(781234.576, "$#,##0.00")
Cells(6, 1) = Format(0.576, "0%")
Cells(7, 1) = Format(0.5768, "0.00%")
End Sub
The output is shown in Figure 9.2
Excel VBA offers a number of financial functions that can be used for accounting and financial calculations. In this lesson, we shall deal some of those functions that perform basic financial calculations. They are PV, FV and Pmt.
PV returns the present value of a certain amount of money a person needs to invest in order to earn a certain amount of money in the future(future value), based on the interest rate and the number of years this amount of money is kept. Additionally, it can also return the present value of an annuity which means the present value of a series of payments in the future
The syntax of PV in Excel VBA is
PV(Rate, Nper, Pmt, FV, Due)
The parameters in the parentheses are explained below: Rate - Interest rate per period
Nper - Number of payment periods
Pmt - Amount of periodic payment for an annuity FV - Future value
Do you know how much you need to invest today and how much you need to save monthly in order to obtain
$1,000,000 thirty years from now? Let'assume a fixed deposit interest rate is 4% per annum and you are willing to save $100 monthly in the bank, you can write the following Excel VBA code to find out the initial investment you need to fork out.
Private Sub CommandButton1_Click() Dim TheRate, FuVal, Payment As Single Dim NPeriod As Integer
TheRate = InputBox("Enter the rate per annum") FuVal = InputBox("Enter future value")
Payment = -InputBox("Enter amount of monthly payment") NPeriod = InputBox("Enter number of years")
MsgBox ("The Initial Investment is " & Round(PV(TheRate / 12 / 100, NPeriod * 12, Payment, FuVal, 1), 2))
End Sub
>
Running the program will produce a series of input boxes where the user can enter various values. The answer is shown in Figure 10.1. The value is negative because this is the amount you need to pay.
FV returns the amount of money you will earn in future by putting in an initital investment and continue to pay certain amount periodically. The amount is depending on the interest rate and the duration. It relects time value of money.
The syntax of FV in Excel VBA is
FV(Rate, Nper, Pmt, PV, Due)
In this example, you want to find the future value if your initial investment is $100,000, your monthly payment is
$100, interest rate 5% and the investment period is 30 years Private Sub CommandButton1_Click()
Dim TheRate, PVal, Payment As Single Dim NPeriod As Integer
TheRate = InputBox("Enter the rate per annum") PVal = InputBox("Enter initial investment amount)
Payment = -InputBox("Enter amount of monthly payment") NPeriod = InputBox("Enter number of years")
MsgBox ("The Initial Investment is " & Round(FV(TheRate / 12 / 100, NPeriod * 12, -Payment, -PVal, 0), 2)) End Sub
We place negative signs infront of paymnet and Pval as you are paying out the money. Running the program will produce a series of input boxes where the user can enter various values. The answer is shown in Figure 10.2. .
Pmt is an Excel VBA function that returns the amount of periodic payments you need to make for a certain PV and FV.
The syntax of Pmt in Excel VBA is Pmt(Rate,Nper, PV, FV, Due) Example 10.3
For example, you borrowed a mortgage loan of 500,000 from the bank to buy a property. You have agreed to pay back the loan in thirty years by a monthly instalment method at an interest rate of 4% per annum. Now you need to calculate the the amount of monthly payment. In this case, Rate=4/100/12 (monthly rate), Nper=30x12=360 months,PV=500,000, FV=0 (loan settled) and due=0 as you normally paying at end of the month.
Private Sub CommandButton1_Click() Dim TheRate, PVal As Single
Dim NPeriod As Integer
TheRate = InputBox("Enter the rate per annum") PVal = InputBox("Enter Loan Amount")
NPeriod = InputBox("Enter number of years")
MsgBox ("The monthly payment is " & Round(Pmt(TheRate / 12 / 100, NPeriod * 12, Pval, 0, 0), 2)) End Sub
Running the program will produce a series of input boxes where the user can enter various values. The answer is shown in Figure 10.3. .The value is negative because this is the amount you need to pay
Excel VBA provides various built-in date and time functions that allows us to process dates and times. We can use date and time functions to display system date and time , add and substract data and time, converting string to date and more.
The date and time functions are explained as follows: Now- returns current system date and time
Date- returns current system date
Day(Date)- Returns the day of the month for the date specified in the argument Weekday(Date)- Returns weekday as an integer for the date specified in the argument
WeekdayName(Weekday(Date))- Returns the name of weekday for the date specified in the argument
WeekdayName(Weekday(Date),True)- Returns the abbrieviated name of weekday for the date specified in the argument
Month(Date)- Returns the month of the year in integer for the date specified in the argument MonthName(Month(Date))- Returns the name of month of the year for the date specified in the argument
MonthName(Month(Date))- Returns the abbrieviated name of month of the year for the date specified in the argument
Year(Date)- Returns the year in integer for the date specified in the argument
Private | Sub | CommandButton1_Click() | ||||||
Cells(1, | 2) | = | Now | |||||
Cells(2, | 2) | = | Date | |||||
Cells(3, | 2) | = | Day(Date) | |||||
Cells(4, | 2) | = | Weekday(Date) | |||||
Cells(5, | 2) | = | WeekdayName(Weekday(Date)) |
Cells(6, 2) = WeekdayName(Weekday(Date), "true")
Cells(7, 2) = Month(Date)
Cells(8, 2) = MonthName(Month(Date)) Cells(9, 2) = MonthName(Month(Date), "true") Cells(10, 2) = Year(Date)
End Sub
The output is as shown in Figure 11.1
The time functions are explained as follows: Time- Returns the current system time Hour- Returns the hour from its argument
Minute- Returns the minute from its argument
Second- Returns the second from its argument
Timer- Returns the number of seconds since midnight
Private Sub CommandButton1_Click()
Cells(1, 2) = Time Cells(2, 2) = Hour(Time)
Cells(3, 2) = Minute(Time) Cells(4, 2) = Second(Time) Cells(5, 2) = Timer
End Sub
The output is shown in Figure 11.2
The DatePart function returns the part of the date specified in the arguments. The arguments are:
YYYY- Year q- Quarter m- Month
Y- Day of Year d- Day
w- Weekday ww- Week
h- Hour n- Minute
s- Second
Private Sub CommandButton1_Click()
Cells(1, 2) = DatePart("YYYY", Now) Cells(2, 2) = DatePart("q", Now) Cells(3, 2) = DatePart("m", Now) Cells(4, 2) = DatePart("y", Now) Cells(5, 2) = DatePart("d", Now) Cells(6, 2) = DatePart("w", Now) Cells(7, 2) = DatePart("ww", Now) Cells(8, 2) = DatePart("h", Now) Cells(9, 2) = DatePart("n", Now) Cells(10, 2) = DatePart("s", Now)
End Sub
The argument Now is to return the current date and time.The output is shown in Figure 11.3
The function DateAdd is to add dates and the DateDiff is the function to substract dates. The syntax of DateAdd is
DateAdd("t",n,date)
Where t indicates the interval of the part of the date to add, either d(day), m(month) or year and n is the value to add.
The syntax of DateDiff is DateDiff("t",date1,date2)
Where t indicates the interval of the part of the date to substract. The interval can be YYYY, m, w, ww, d, h, n, s, same as parameters for DatePart. The function with calculate the difference between date1 and date2.
Private Sub CommandButton1_Click()
Cells(1, 2) = Now
Cells(2, 2) = DateAdd("yyyy", 2, Now)
Cells(3, 2) = DateAdd("m", 10, Now)
Cells(4, 2) = DateAdd("d", 100, Now)
Cells(5, 2) = DateAdd("h", 10, Now)
Cells(6, 2) = DateAdd("YYYY", 3, "2015/3/28")
Cells(7, 2) = DateDiff("YYYY", Now, "2020/4/16") Cells(8, 2) = DateDiff("m", Now, "2020/4/16") Cells(9, 2) = DateDiff("ww", Now, "2020/4/16") Cells(10, 2) = DateDiff("d", Now, "2020/4/16")
Cells(11, 2) = DateDiff("YYYY", "2016/5/20", "2020/4/16")
Cells(12, 2) = DateDiff("m", "2016/5/20", "2020/4/16")
End Sub
The output is shown in Figure 11.4
In this lesson, we shall learn how to create Excel VBA using If..Then...ElseIf statement to control program flow and enables decision making based on certain conditions. To control program flow, we use the If...Then...ElseIf structure together with conditional and logical operators.
Conditional and Logical Operators
To control the Visual Basic program flow, we can use various conditional operators. Basically, they resemble mathematical operators. Conditional operators are very powerful tools, they let the VB program compare data values and then decide what action to take, whether to execute a program or terminate the program and more. These operators are shown in Table 2.1.
= | Equal to |
> | More than |
< | Less Than |
>= | More than or equal |
<= | Less than or equal |
<> | Not Equal to |
And | Both sides must be true |
or | One side or other must be true |
Xor | One side or other must be true but not both |
Not | Negates truth |
To control the Visual Basic program flow, we shall use If...Then...Else statement together with the conditional operators and logical operators.
The syntax of the if...then...else statement is
VB expressions
ElseIf
VB expressions
Else
VB expressions
<pEnd If
</p
any If..Then..Else statement must end with End If. Sometime it is not necessary to use Else.
In this example, you place the command button1 on the MS Excel spreadsheet and go into the VB editor by clicking on the button. At the Excel VB editor, key in the program codes as shown on the left.
I use randomize timer and the RND function to generate random numbers. In order to generate random integers between 0 and 100, I combined the syntax Int(Rnd*100). For example, when Rnd=0.6543, then Rnd*100=65.43, and Int(65.43)=65. Using the statement cells(1,1).Value=mark will place the value of 65 into cell(1,1).
Now, based on the mark in cells(1,1), I use the If.......Then....Elseif statements to put the corresponding grade in cells(2,1). So, when you click on command button 1, it will put a random number between 1 and 100 in cells(1,1) and the corresponding grade in cells(2,1).
The Code
Private Sub CommandButton1_Click() Dim mark As Integer
Dim grade As String Randomize Timer mark = Int(Rnd * 100)
Cells(1, 1).Value = mark
If mark < 20 And mark >= 0 Then grade = "F"
Cells(2, 1).Value = grade
ElseIf mark < 30 And mark >= 20 Then grade = "E"
Cells(2, 1).Value = grade
ElseIf mark < 40 And mark >= 30 Then grade = "D"
Cells(2, 1).Value = grade
ElseIf mark < 50 And mark >= 40 Then grade = "C-"
Cells(2, 1).Value = grade
ElseIf mark < 60 And mark >= 50 Then grade = "C"
Cells(2, 1).Value = grade
ElseIf mark < 70 And mark >= 60 Then grade = "C+"
Cells(2, 1).Value = grade
ElseIf mark < 80 And mark >= 70 Then grade = "B"
Cells(2, 1).Value = grade
ElseIf mark <= 100 And mark >=80 Then grade = "A"
Cells(2, 1).Value = grade End If
End Sub
Lesson 13: Select Case.........End Select
The Select Case control structure also involves decisions making but it slightly different from the If...Then...ElseIf control structure . The If ...Then...ElseIf statement control structure evaluates only one expression but each ElseIf
statement computes different values for the expression. On the other hand, the Select Case control structure evaluates one expression for multiple values. Select Case is preferred when there exist multiple conditions as using If...Then...ElseIf statements will become too messy. .
The syntax of the Select Case...End Select structure is as follow Select Case variable
Case value 1 Statement Case value 2 Statement Case value 3 Statement
.
.
Case Else End Select
In the following example, we shall show you how to process the grades of students according to the marks given.
Private Sub CommandButton1_Click()
Dim mark As Single Dim grade As String mark = Cells(1, 1).Value
'To set the alignment to center
Range("A1:B1").Select With Selection
.HorizontalAlignment = xlCenter End With
Select Case mark Case 0 To 20 grade = "F"
Cells(1, 2) = grade Case 20 To 29 grade = "E" Cells(1, 2) = grade Case 30 To 39 grade = "D" Cells(1, 2) = grade Case 40 To 59 grade = "C" Cells(1, 2) = grade Case 60 To 79 grade = "B" Cells(1, 2) = grade Case 80 To 100 grade = "A" Cells(1, 2) = grade Case Else
grade = "Error!" Cells(1, 2) = grade End Select
End Sub
Explanation:
To set the cell align alignment to center, we use the following procedure:
Range("A1:B1").Select | ||
With | Selection | |
.HorizontalAlignment | = | xlCenter |
End With |
We can use the statement case value1 to value 2 to specify the range of values that fulfill the particular case.
You should also include the error case where the values entered are out of the range or invalid. For example, if the examination mark is from 0 to 100, then any value out of this range is invalid. In this program, we use case else to handle the error entries.
The Figure below shows the output of this example.
In lesson 12, we have learned how to handle decisions making process using If...Then...Else struture. Another procedure that involves decisions making is looping. Excel VBA allows a procedure to repeat many times until a condition or a set of conditions is fulfilled. This is generally called looping . Looping is a very useful feature of Excel VBA because it makes repetitive works easier. There are two kinds of loops in Excel VBA,
the For.......Next loop and the Do...Loop . In this lesson, we shall deal with with the For...Next Loop and we shall learn the Do...Loop in the next lesson.
The For....Next Loop event procedure is written as follows: For counter=startNumber to endNumber (Step increment) One or more statements
Next
To demonstrate the For....Next loop in Excel VBA, here are two examples:
Private Sub CommandButton1_Click() Dim i As Integer For i = 1 To 10
Cells(i, 1).Value = i
Next End Sub
In this Excel VBA program, you place the command button 1 on the spreadsheet then click on it to go into the Visual Basic editor. When you click on the button , the Excel VBA program will fill cells(1,1) with the value of 1, cells(2,1) with the value of 2, cells(3,1) with the value of 3......until cells (10,1) with the value of 10. The position of each cell in the Excel spreadsheet is referenced with cells(i,j), where i represents row and j represent column.
In Example 2,we use the nested loop to put the values of i+j from cells(1,1),cells(1,2),cells(1,3),cells(1,4),cells(1,5) ..........until cells(10,5). The code and output are shown below.
Private Sub CommandButton1_Click() Dim i, j As Integer
For i = 1 To 10
For j = 1 To 5
Cells(i, j).Value = i + j
Next j Next i End Sub
For........Next loop to execute a repetitive process. In this lesson, you will learn to work with two more types of loops, the Do Loop and theWhile...Wend loop.
There are four ways you can use the Do Loop as show below:
i) Do...........Loop While
Do until.............Loop
Do while............Loop
Do............Loop until
Example 15.1:
Arranging numbers in ascending order
Private Sub CommandButton1_Click() Dim counter As Integer
Do
counter = counter + 1 Cells(counter, 1) = counter Loop While counter < 10
End Sub
In this example, the program will keep on adding 1 to the preceding counter value as long as the counter value is less than 10. It displays 1 in cells(1,1), 2 in cells(2,1)….. until 10 in cells (10,1).
Example 15.2:
Arranging numbers in descending order
Private Sub CommandButton1_Click() Dim counter As Integer
Do Until counter = 10 counter = counter + 1
Cells(counter, 1) = 11 - counter Loop
End Sub
In this example, the program will keep on adding 1 to the preceding counter value until the counter value reaches 10. It displays 10 in cells(1,1), 9 in cells(2,1)….. until 1 in cells (10,1).
Examle 15.3
Private Sub CommandButton1_Click() Dim counter , sum As Integer
'To set the alignment to center
Range("A1:C11").Select With Selection
.HorizontalAlignment = xlCenter End With
Cells(1, 1) = "X"
Cells(1, 2) = "Y"
Cells(1, 3) = "X+Y"
Do While counter < 10 counter = counter + 1 Cells(counter + 1, 1) = counter
Cells(counter + 1, 2) = counter * 2
sum = Cells(counter + 1, 1) + Cells(counter + 1, 2)
Cells(counter + 1, 3) = sum Loop
End Sub
In this example, the program will display the values of X in cells(1,1) to cells(11,1). The value of Y is X2 and the values are display in column 2, i.e. from cells(2,1) to cells(2,11). Finally, it shows the values of X+Y in column 3, i.e. from cells(3,1) to cells(3,11)
The results are shown in the following figures:
The structure of a While...Wend Loop is very similar to the Do Loop. it takes the following form:
While condition Statements
Wend
In this example, we add a list box to display a series of numbers and the sum of those numbers. The process of displaying and adding the numbers starting from n=0 till n=19. The process stops when n=20.
Private Sub CommandButton1_Click() ListBox1.Clear
Dim sum, n As Integer While n <> 20
n = n + 1
sum | = | sum | + | n | ||||
ListBox1.AddItem | (n | & | vbTab | & | sum) |
Cells(n | + | 1, | 2) | = | n | |
Cells(n | + | 1, | 3) | = | sum | |
Wend |
End Sub
The output is shown in the Figure below
In this lesson, we shall explore how to create Excel VBA that can format the color of an Excel spreadsheet. Using VBA codes, we can change the font color and the the background color of each cell .We shall also learn to write an Excel VBA program that can create random font and background colors. Colors can be assigned using a number of methods in Excel VBA, but we shall focus on the RGB function. The RGB function has three numbers
corresponding to the red, green and blue components. The range of values of the three numbers is from 0 to
255. A mixture of the three primary colors will produce different colors.
The format to set the font color is
cells(i,j).Font.Color=RGB(x,y,x), where x ,y , z can be any number between 1 and 255 For example
cells(1,1).Font.Color=RGB(255,255,0) will change the font color to yellow The format to set the cell's background color is
cells(i,j).Interior.Color=RGB(x,y,x), where x ,y , z can be any number between 1 and 255
In the following example, the font color in cells(1,1) and background color in cells(2,1) are changing for every click of the command button due to the randomized process.
Private Sub CommandButton1_Click()
Randomize Timer
Dim i, j, k As Integer
i = Int(255 * Rnd) + 1
j = Int(255 * Rnd) + 1
k = Int(255 * Rnd) + 1
Cells(1, 1).Font.Color = RGB(i, j, k)
Cells(2, 1).Interior.Color = RGB(j, k, i)
End Sub
Explanation:
Rnd is a random number between 0 and 1
255* Rnd will produce a number between 0 and 255
Int(255*Rnd) will produce integers that take the values from 0 to 254 So we need to add 1 to get random integers from 0 to 255.
example; Rnd=0.229
255*Rnd=58.395 Int(58.395)=58
Most programming languages today deal with objects, a concept called object oriented programming. Although Excel VBA is not a truly object oriented programming language, it does deal with objects. VBA object is something like a tool or a thing that has certain functions and properties, and can contain data. For example, an Excel Worksheet is an object, cell in a worksheet is an object, range of cells is an object, font of a cell is an object, a command button is an object, and a text box is an object and more.
In order to view the VBA objects, you can insert a number of objects or controls into the worksheet, and click the command button to go into the code window. The upper left pane of the code window contains the list of objects you have inserted into the worksheet; you can view them in the dropdown dialog when you click the down arrow. The right pane represents the events associated with the objects, as shown in Figure 19.1 below.
To view all the available Excel VBA objects, you can click on the objects browser in the code window
17.2: Object Properties
An Excel VBA object has properties and methods. Properties are like the characteristics or attributes of an object. For example, Range is an Excel VBA object and one of its properties is value. We connect an object to its property by a period(a dot or full stop). The following example shows how we connect the property value to the Range object.
Private Sub CommandButton1_Click()
Range("A1:A6").Value = 10 End Sub
In this example, by using the value property, we can fill cells A1 to A6 with the value of 10. However, because value is the default property, it can be omitted. So the above procedure can be rewritten as
Private Sub CommandButton1_Click() Range("A1:A6")= 10
End Sub
Cells is also an Excel VBA object, but it is also the property of the range object. So an object can also be a property, it depends on the hierarchy of the objects. Range has higher hierarchy than cells, and interior has lower hierarchy than Cells, and color has lower hierarchy than Interior, so you can write
Range("A1:A3").Cells(1, 1).Interior.Color = vbYellow
This statement will fill cells (1,1) with yellow color. Notice that although the Range object specifies a range from A1 to A3, but the cells property specifies only cells(1,1) to be filled with yellow color, it sort of overwrite the range specified by the Range object.
Another object is font that belong to the Range object. And font has its properties.For example, Range(“A1:A4”).Font.Color=vbYellow , the color property of the object Font will result in all the contents from cell A1 to cell A4 to be displayed in yellow color.
Sometime it is not necessary to type the properties, Excel VBA IntelliSense will display a drop-down list of proposed properties after you type a period at the end of the object name. You can then select the property you want by double clicking the it or by highlighting it then press the Enter key. The IntelliSense drop-down is shown in Figure 17.3
Besides having properties, Excel VBA objects usually also have methods. Methods normally do something or perform certain operations. For example, ClearContents is a method of the range object. It clears the contents of a cell or a range of cells.
You can write the following code to clear the contents:
Private Sub CommandButton1_Click() Range(“A1:A6”).ClearContents
End Sub
You can also let the user select his own range of cells and clear the contents by using the InputBox function, as shown in Example 18.2
Private Sub CommandButton1_Click()
Dim, | selectedRng | As | String | |||
selectedRng | = | InputBox("Enter | your | range") |
Range(selectedRng).ClearContents
End Sub
In order to clear the contents of the entire worksheet, you can use the following code: Sheet1.Cells.ClearContents
But if you only want to clear the formats of an entire worksheet, you can use the following syntax: Sheet1.Cells.ClearFormats
To select a range of cells, you can use the Select method. This method selects a range of cells specified by the Range object. The syntax is
Range(“A1:A5”).Select
Private Sub CommandButton1_Click() Range("A1:A5").Select
End Sub
Example 18.4
This example allows the user to specifies the range of cells to be seleted. Private Sub CommandButton1_Click()
Dim selectedRng As String
selectedRng = InputBox("Enter your range") Range(selectedRng).Select
End Sub
To deselect the selected range, we can use the Clear method. Range(“CiRj:CmRn”).Clear
In this example, we insert two command buttons, the first one is to select the range and the second one is to deselect the selected range.
Private Sub CommandButton1_Click() Range("A1:A5").Select
End Sub
Private Sub CommandButton2_Click() Range("A1:A5").Clear
End Sub
Instead of using the Clear method, you can also use the ClearContents method.
Another very useful method is the Autofill method. This method performs an autofill on the cells in the specified range with a series of items including numbers, days of week, months of year and more. The format is
Expression.AutoFill(Destination, Type)
Where Expression can be an object or a variable that returns and object. Destination means the required Range object of the cells to be filled. The destination must include the source range. Type means type of series, such as days of week, month of year and more. The AutoFill type constant is something like xlFillWeekdays, XlFillDays, XlFillMonths and more.
Private Sub CommandButton1_Click() Range(“A1”)=1
Range(“A2”)=2
Range("A1:A2").AutoFill Destination:=Range("A1:A10") End Sub
In this example, the source range is A1 to A2. When the user clicks on the command button, the program will first fill cell A1 with 1 and cell A2 will 2, and then automatically fills the Range A1 to A10 with a series of numbers from 1 to 10.
Private Sub CommandButton1_Click() Cells(1, 1).Value = "monday"
Cells(2, 1).Value = "Tuesday"
Range("A1:A2").AutoFill Destination:=Range("A1:A10"), Type:=xlFillDays End Sub
This example allows the user to select the range of cells to be automatically filled using the Autofill method. This can be achieved with the use of the InputBox. Since each time we want to autofill a new range, we need to clear the contents of the entire worksheet using the Sheet1.Cells.ClearContents statement.
Private Sub CommandButton1_Click() Dim selectedRng As String Sheet1.Cells.ClearContents
selectedRng = InputBox("Enter your range") Range("A1") = 1
Range("A2") = 2
Range("A1:A2").AutoFill Destination:=Range(selectedRng) End Sub
Range is one of the most important and most commonly used Excel VBA object. In fact, we have dealt with the Range object in previous lessons.
The Range object contains two arguments that specifies a selected area on the spreadsheet. The syntax is
For example, Range("A1:C6") means the specified range is from cell A1 to C6. To select the specified range, the syntax is
where select is a method of the Range object
Private Sub CommandButton1_Click() Range("A1:C6").Select
End Sub
The columns property of the Range object is to select a certain columns in the particular range specified by the Range object. The syntax isM/p>
This example select column C in the range A1 to C6 Private Sub CommandButton2_Click()
Range("A1:C6").Columns(3).Select End Sub
You may also use Cells(1,1) to Cells(6,3) instead of A1:C6, the syntax is
The output is as shown in Figure 19.1
You can also format font the cells in a particular column in terms of type, color, bold,italic, underlined and size using the With Range...End With Structure. It can also be used to format other Range properties like background color. Using With Range....End With structure can save time and make the code leaner.
Private Sub CommandButton1_Click() With Range("A1:C6").Columns(2)
.Font.ColorIndex = 3
.Font.Bold = True
.Font.Italic = True
.Font.Underline = True
.Font.Name = "Times New Roman"
.Font.Size = 14
.Interior.Color = RGB(255, 255, 0) End With
End Sub
Without using With Range...End With, you need to write every line in full, like this
Basically the syntax for the Rows property is similar to that of the Columns property, you just need to replace Columns with rows. The syntax of selecting a row within a certain range is
This following code selects the third row within the range A1 to F3 Private Sub CommandButton2_Click() Range("A1:F3").Rows(3).Select
End Sub
Private Sub CommandButton1_Click() With Range("A1:F3").Rows(2)
.Font.ColorIndex = 3
.Font.Bold = True
.Font.Italic = True
.Font.Underline = True
.Font.Name = "Times New Roman"
.Font.Size = 14
.Interior.Color = RGB(255, 255, 0) End With
End Sub
Using the Set keyword to Declare Range
We can write Excel VBA code that can specifies certain range of cells using the set keyword and then perform certain tasks according to a set of conditions. In Example 19.6, we shall write the ExcelVBA code such that it can accept range input from the user and then change the mark to blue if it is more than or equal to 50 and change it to red if the mark is less than 50.
Private Sub CommandButton1_Click()
Dim rng, cell As Range, selectedRng As String
.selectedRng = InputBox("Enter your range")
.Set rng = Range(selectedRng)
.For Each cell In rng
.If cell.Value >= 50 Then
.cell.Font.ColorIndex = 5
.Else
.cell.Font.ColorIndex = 3
.End If
.Next cell
.End Sub
The InputBox function is used to accept value from the users.
rng and cell are declared as a Range variable using the Dim statement while selectedRng is declared as a string that receive input from the user. Once the input is obtained from the user, it is stored using the Set method and the Range function.
For Each cell In rng...Net cell is a loop that can iterate through the selected range, one cell at a time. The If...Then...Else statements are to specify the color of the font according to the range of values determined by the conditions.
You can use the Formula property of the Range object to write your own customized formula.
Private Sub CommandButton1_Click() Range("A1:B3").Columns(3).Formula = "=A1+B1" End Sub
In this example, the formula A1+B1 will be copied down column 3 (column C) from cell C1 to cell C3. The program automatically sums up the corresponding values down column A and column B and displays the results in column C, as shown in Figure 19.6
The above example can also be rewritten and produces the same result as below: Range("A1:B3").Columns(3).Formula = "=Sum(A1:B1)"
There are many formulas in Excel VBA which we can use to simplify and speed up complex calculations. The formulas are categorized into Financial, Mathematical, Statistical, Date ,Time and others. For example, in the statistical category, we have Average (Mean), Mode and Median
In this example, the program computes the average of the corresponding values in column A and column B and displays the results in column C. For example, the mean of values in cell A1 and Cell B1 is computed and displayed in Cell C1. Subsequent means are automatically copied down Column C until cell C3.
Private Sub CommandButton1_Click()
Range("A1:B3").Columns(3).Formula = "=Average(A1:B1)"
End Sub
In this example, the program computes the mode for every row in the range A1:E4 and displays them in column
F. It also makes the font bold and red in color, as shown in Figure 19.6. Private Sub CommandButton1_Click() Range("A1:E4").Columns(6).Formula = "=Mode(A1:E1)" Range("A1:E4").Columns(6).Font.Bold = True Range("A1:E4").Columns(6).Font.ColorIndex = 3
End Sub
The Worksheet Properties in Excel VBA
Similar to the Range Object, the Worksheet has its own set of properties and methods. When we write Excel VBA code involving the Worksheet object, we use Worksheets.
The reason is that we are dealing with a collection of worksheets most of the time, so using Worksheets enables us to manipulate multiple worksheets at the same time. Some of the common properties of the worksheet
are name, count, cells, columns, rows and columnWidth.
Private Sub CommandButton1_Click() MsgBox Worksheets(1).Name
End Sub
Running the code will produce a pop-up dialog that displays the worksheet name as sheet 1, as shown in Figure 19.1.
The count property returns the number of worksheets in an opened workbook.
Private Sub CommandButton1_Click() MsgBox Worksheets.Count
End Sub
The output is shown in Figure 20.2.
The count property in this example will return the number of columns in the worksheet. Private Sub CommandButton1_Click()
MsgBox Worksheets(1).Columns.Count End Sub
The output is shown below:
The count property in this example will return the number of rows in the worksheet. Private Sub CommandButton1_Click()
MsgBox Worksheets(1).Rows.Count End Sub
Some of the worksheet methods are add, delete, select, SaveAs, copy, paste and more.
Private Sub CommandButton1_Click()
'Add a new worksheet Worksheets. Add End Sub
Private Sub CommandButton2_Click()
'Delete a worksheet Worksheets(1).Delete End Sub
The select method associated with worksheet lets the user select a particular worksheet. In this example, worksheet 2 will be selected.
Private Sub CommandButton1_Click() 'Worksheet 2 will be selected Worksheets(2).Select
End Sub
The select method can also be used together with the Worksheet抯 properties Cells, Columns and Rows as shown in the following examples.
Private Sub CommandButton1_Click() 'Cell A1 will be selected
Worksheets (1).Cells (1).Select End Sub
Private Sub CommandButton1_Click()
'Column 1 will be selected Worksheets (1).Columns (1).Select End Sub
Private Sub CommandButton1_Click() 'Row 1 will be selected
Worksheets (1).Rows (1).Select 'Row 1 will be selected
End Sub
Excel VBA 2010 also allows us to write code for copy and paste. Let抯 look at the following Example:
Private Sub CommandButton1_Click() 'To copy the content of a cell 1 Worksheets(1).Cells(1).Select Selection.Copy
End Sub
Private Sub CommandButton2_Click() 'To paste the content of cell 1 to cell 2 Worksheets(1).Cells(2).Select ActiveSheet.Paste
In previous lesson, we have learned to write code associated with the worksheet object in Excel VBA 2010. In this lesson, we shall learn about the Workbook object . The Workbook object at the top of the hierarchy of the Excel VBA 2010 objects. We will deal with properties and methods associated the Workbook object.
When we write Excel VBA code involving the Workbook object, we use Workbooks. The reason is that we are dealing with a collection of workbooks most of the time, so using Workbooks enables us to manipulate multiple workbooks at the same time. When will deal with multiple workbooks, we can use indices to denote different workbooks that are open, using the syntax Workbooks (i), where i is an index. For example, Workbooks (1) denotes Workbook1, Workbooks (2) denotes Workbook2 and more. Workbooks have a number of properties. Some of the common properties are Name, Path and FullName Let's look at the following example:
Private Sub CommandButton1_Click() MsgBox Workbooks(1).Name
End Sub
The program will cause a message dialog box to pop up and displays the first workbook name, i.e. Book1 as shown in Figure 20.1 below:
If we have only one open workbook, we can also use the syntax ThisWorkbook in place of Workbook (1), as follows:
Private Sub CommandButton1_Click () MsgBox ThisWorkbook.Name
End Sub
Private Sub CommandButton1_Click () MsgBox ThisWorkbook.Path
End Sub
Or you can use the following code: Private Sub CommandButton1Click () MsgBox Workbooks ("Book1").Path End Sub
The Output is shown in Figure 21.2
This example will display the path and name of the opened workbook. The code is: Private Sub CommandButton1_Click ()
MsgBox ThisWorkbook.FullName
End Sub
Or
Private Sub CommandButton1Click() MsgBox Workbooks("Book1").Fullname End Sub
The output is shown in Figure 21.3.
There are a number of methods associated with the workbook object. These methods are Save, SaveAs, Open, Close and more.
In this example, when the user clicks on the command button, it will open up a dialog box and ask the user to specify a path and type in the file name, and then click the save button, not unlike the standard windows SaveAs dialog, as shown in Figure 21.4.
Private Sub CommandButton1_Click() fName = Application.GetSaveAsFilename ThisWorkbook.SaveAs Filename:=fName End Sub
Another method associated with the workbook object is open. The syntax is Workbooks.Open ("File Name")
In this example, when the user click on the command button, it wil open the file book1.xls under the path燙:\Users\Toshiba\Documents\Liew Folder\VBA\vba2010\
Private Sub CommandButton1_Click()
Workbooks.Open ("C:\Users\Toshiba\Documents\Liew Folder\VBA\vba2010\book1.xlsx") End Sub
The close method is the command that closes a workbook. The syntax is Workbooks (i).Close
In this example, when the user clicks the command button, it will close Workbooks (1). Private Sub CommandButton1_Click()
Workbooks (1).Close End Sub
In Excel VBA , the Check box is a very useful control . It allows the user to select one or more items by checking the check box or check boxes concerned. For example, you may create a shopping cart where the user can click on check boxes that correspond to the items they intend to buy, and the total payment can be computed at the same time. One of most important properties of the check box in Excel VBA 2010 is Value. If the check box is selected or checked, the value is true, whilst if it is not selected or unchecked, the Value is False.
The usage of check box is illustrated in Example 22.1
In this example, the user can choose to display the sale volume of one type of fruits sold or total sale volume. The code is shown below:
Private Sub CommandButton1_Click()
If CheckBox1.Value = True And CheckBox2.Value = False Then MsgBox "Quantity of apple sold is" & Cells (2, 2).Value
ElseIf CheckBox2.Value = True And CheckBox1.Value = False Then MsgBox "Quantity of orange sold is " & Cells(2, 3).Value
Else
MsgBox "Quantity of Fruits sold is" & Cells (2, 4).Value End If
End Sub
The output Interface is shown in Figure 22.1
Option Button
The option button control also lets the user selects one of the choices. However, two or more option buttons must work together because as one of the option buttons is selected, the other option button will be deselected. In fact, only one option button can be selected at one time. When an option button is selected, its value is set to "True" and when it is deselected; its value is set to "False".
Example 22.2
This example demonstrates the usage of the option buttons. In this example, the Message box will display which option button selected by the user. The output interface is shown in Figure 22.2.
Private Sub CommandButton1_Click() If OptionButton1.Value = True Then
MsgBox "Option1 is selected"
ElseIf OptionButton2.Value = True Then MsgBox "Option2 is selected"
Else
MsgBox "Option3 is selected" End If
End Sub
We have learned how to work with check boxes, option buttons and text boxes in Excel VBA in the previous lessons. We shall continue to learn how to manipulate other controls in Excel VBA 2010 in this lesson. In this lesson, we will deal with List Box, Combo Box and Toggle Button.
The function of the List Box is to present a list of items where the user can click and select the items from the list.
To add items to the list, we can use the AddItem method. To clear all the items in the List Box, you can use the Clear method. The usage of Additem method and the Clear method is shown Example 23.1.
Example 23.1
Private Sub CommandButton1_Click() For x = 1 To 10
L; istBox1.AddItem "Apple" Next
End Sub
'To clear the List Box
Private Sub CommandButton2_Click() For x = 1 To 10
ListBox1.Clear Next
End Sub
>
The function of the Combo Box is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the small arrowhead on the right of the combo box to see the items which are presented in a drop-down list. In order to add items to the list, you can also use the AddItem method.
Private Sub CommandButton1_Click() ComboBox1.Text = "Apple"
For x = 1 To 10 ComboBox1.AddItem "Apple" Next
End Sub
'To clear the combo box
Private Sub CommandButton2_Click() ComboBox1.Clear
End Sub
Toggle button lets the user switches from one action to another alternatively. When the Toggle button is being depressed, the value is true and when it is not depressed, the value is false. By using the If and Else code structure, we can thus switch from one action to another by pressing the toggle button repeatedly.
In this example, the user can toggle between apple and orange as well as font colors. Private Sub ToggleButton1_Click ()
If ToggleButton1.Value = True Then Cells (1, 1).Font.Color = vbRed Else
Cells (1, 1) = "Orange"
Cells (1, 1).Font.Color = vbBlue End If
End Sub
View the animated image in Figure 23.3
In Excel VBA , we can write code to create charts and graphs easily based on the data on the spreadsheet. Excel VBA has made charting engine as part of the Shape object. It is also an object by itself. 燱e can create charts on
a sheet of their own or embed them into an 爀xisting worksheet. The chart sheet is the Chart object whereas the embedded chart is part of the shape collection for the worksheet.
To create a pie chart in a spreadsheet, first of all you need to enter a range of data in spreadsheet. After entering the data, you need to name the range by right-clicking the range and clicking define name in the pop-up menu. Name the chart MyChart Now insert a command button and then click it to enter the following code in the Excel VBA editor
Private Sub CommandButton1_Click() ActiveSheet.Shapes.AddChart.Select ActiveSheet.Shapes(1).Top = 10
ActiveSheet.Shapes(1).Left = 10 ActiveChart.ChartType = xl3DPie ActiveChart.PlotArea.Select ActiveChart.SetSourceData Source:=Range("MyChart") ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = "My Chart" End Sub
To separate the pie chart into slices (The technical term is explode), you can add this line to the code: ActiveChart.SeriesCollection(1).Explosion = 10
As there are five sectors, setting the explosion value to 10 explode all slices. You will get the following chart:
To draw a bar graph, you just need to change the ChartType to牋xl3DColumn. Private Sub CommandButton2_Click()
ActiveSheet.Shapes.AddChart.Select ActiveSheet.Shapes(1).Top = 10
ActiveSheet.Shapes(1).Left = 10 ActiveChart.ChartType = xl3DColumn ActiveChart.PlotArea.Select ActiveChart.SetSourceData Source:=Range("MyChart") ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = "My Chart" End Sub
Excel VBA 2010 has built-in parameters to define the types of charts that can be drawn on a spreadsheet. 燳ou can refer to the parameters as the ChartType properties. The list of common properties for ChartType are listed below:
Property | Chart Type |
xlArea | Area Chart |
xlBar | Bar Chart |
xlColumn | Column Chart |
xlLine | Line Chart |
xlPie Pie Chart xlXYScatter XY Scatter Chart xl3DArea 3D Area Chart
xl3DBar 3D Bar Chart
xl3DColumn 3D Column Chart Xl3DLine 3D Line Chart
For example, if you change the ChartType property to xlLine using the code ActiveChart.ChartType = xlLine
you can get a line graph as follow:
Animation can be achieved by changing the position of an object continuously using a looping sub procedure. Two properties or functions that are required to change the positions or coordinates of the object are
the Left and Top properties. The Left property specifies the distance of the left edge of the object in pixel from the left border of the screen and the Top property specifies the distance of the top edge of the object from the top border of the screen.
For for example, the following code makes the object move from left to right then back to left again repeatedly until the user press the stop button. The reset button move the object back to the starting position.
Beside creating VBA code for mathematical and financial calculations, it is also possible to creating some fun applications in Excel VBA, including games and animation. Although professionals programmers might not be interested to write such applications, it is worth while trying them out as a hobby and for personal satisfaction.
Private Sub StartButton_Click() repeat:
With VBAProject.Sheet1.Image1
.Left = .Left + 1 DoEvents
If .Left > 200 Then .Left = 1 End With
GoTo repeat
End Sub
If you wish to move the object up and down, change the above code by replacing the property Left to Top, the code appear as follows:
Private Sub StartButton_Click() repeat: | ||||
With .Top= | .Top+ | VBAProject.Sheet1.Image1 1 | ||
DoEvents If .Top> | 200 | Then | .Top | = 1 |
End | With | |||
GoTo repeat | ||||
End Sub |
If you wish to make the object move diagonally, then use the properties Top and Left at the same time, as follows:
Private Sub StartButton_Click() repeat:
With VBAProject.Sheet1.Image1
.Top = .Top + 5
.Left = .Left + 5
DoEvents
If .Top > 200 Then .Top = 1 If .Left > 200 Then .Left = 1
End With GoTo repeat
End Sub